package com.siruier.boss.ui.tool.image.select.service.intercept

import android.content.Context
import android.net.Uri
import android.text.TextUtils
import android.webkit.MimeTypeMap
import cn.hutool.core.io.file.FileNameUtil
import com.alibaba.fastjson.JSON
import com.luck.picture.lib.config.PictureMimeType
import com.siruier.boss.api.LOGIN_API_SERVICE
import com.siruier.boss.api.core.toData
import com.siruier.boss.ui.AppCore
import com.siruier.boss.ui.tool.image.select.domain.ImageSelectBean
import com.siruier.boss.ui.tool.image.select.service.ImageSelectIntercept
import com.siruier.boss.ui.tool.image.select.service.ImageUploadUBuilder
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File
import java.util.*

object ApiUploadFileIntercept : ImageSelectIntercept {
    override suspend fun intercept(
        config: ImageUploadUBuilder,
        localMedias: MutableList<ImageSelectBean>?
    ): MutableList<ImageSelectBean>? {
        if (config.isUp) {
            uploadFile(config.path, localMedias)
        }
        return localMedias
    }

    suspend fun uploadFile(path: String, localMedias: MutableList<ImageSelectBean>?) {
        localMedias?.forEach {
            if (it.url.isNullOrEmpty()){
                val builder: MultipartBody.Builder = MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                val mediaType: MediaType = getMimeTypeFromMediaContentUri(AppCore.app, it.path).toMediaType()
                val fileName: String?
                val fileRequestBody = if (it.path.startsWith("content://")) {
                    fileName = it.fileName
                    AppCore.app.contentResolver.openInputStream(Uri.parse(it.path)).use { stream ->
                        stream?.readBytes()?.toRequestBody(mediaType)
                    }
                } else {
                    fileName = FileNameUtil.getName(it.path)
                    File(it.path).asRequestBody(mediaType)
                }
                if (fileRequestBody != null) {
                    builder.addFormDataPart(
                        "file",
                        fileName,
                        fileRequestBody
                    )
                    builder.addFormDataPart("path", path)
                }
                it.url = LOGIN_API_SERVICE.fileUpload(builder.build()).toData()?.url ?: ""
            }
        }
    }

    private fun getMimeTypeFromMediaContentUri(context: Context, uri: String): String {
        val mimeType = if (uri.startsWith("content://")) {
            context.contentResolver.getType(Uri.parse(uri))
        } else {
            val fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri)
            MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.lowercase(Locale.getDefault()))
        }
        return if (TextUtils.isEmpty(mimeType)) PictureMimeType.MIME_TYPE_JPEG else mimeType!!
    }
}